﻿using System;
using System.Threading;
using System.Runtime.InteropServices;

namespace Tickz.Commonz
{
    /// <summary>
    /// 用来记录纳秒时间的
    ///  private void Test()
        //{
        //    PerformanceTimer timer = new PerformanceTimer();
        //    timer.Start();
        //    ///中间需要计时的代码
        //    ///......
        //    ///中间需要计时的代码
        //    timer.Stop();
        //    Console.Write("{0:F}\t", timer.Duration);//输出时间。。。
        //}
    /// </summary>
    public class PerformanceTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
          out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
          out long lpFrequency);

        private long startTime, stopTime;
        private long freq;

        public PerformanceTimer()
        {
            startTime = 0;
            stopTime = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                throw new Exception("Timer not supported.");
            }
        }

        public void Start()
        {
            Thread.Sleep(0);
            QueryPerformanceCounter(out startTime);
        }

        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double)freq;
            }
        }
    }
}

    
